package webEquipeRechercheGwt.client.allEntityShowingPanel;

import java.util.ArrayList;
import java.util.Collection;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;

import webEquipeRechercheGwt.client.callback.consultation.CallBackGetAllPerson;
import webEquipeRechercheGwt.client.callback.consultation.commands.CommandGetAllPersonsImplAllPersonPanel;
import webEquipeRechercheGwt.client.entityMirror.PersonMirror;
import webEquipeRechercheGwt.client.handler.navigation.ClickHandlerGetPersonCreationLabel;
import webEquipeRechercheGwt.client.handler.navigation.ClickHandlerPerson;
import webEquipeRechercheGwt.client.services.PersonService;
import webEquipeRechercheGwt.client.services.PersonServiceAsync;
import webEquipeRechercheGwt.client.structure.DataShowingPanel;

public class AllPersonPanel extends AllEntityShowingPanel {

	private DataShowingPanel mainPanel;
	private Collection<PersonMirror> persons;
	
	public AllPersonPanel(DataShowingPanel mainPanel) {
		super();
		this.mainPanel = mainPanel;
		persons = new ArrayList<PersonMirror>();
	}

	@Override
	protected void onLoad() {
		super.onLoad();
		updateLabels();
		loadPersonsFromServer();
	}
	
	private void loadPersonsFromServer(){
		PersonServiceAsync service = GWT.create(PersonService.class);
		AsyncCallback<Collection<PersonMirror>> callback = new CallBackGetAllPerson(new CommandGetAllPersonsImplAllPersonPanel(this));
		service.getPersons(callback);
	}

	public void setPersons(Collection<PersonMirror> persons) {
		this.persons = persons;
		updateLabels();
	}
	
	private void addCreationLink(){
		Button b = new Button("create new Person");
		ClickHandler handler = new ClickHandlerGetPersonCreationLabel(mainPanel);
		b.addClickHandler(handler);
		add(b);
	}
	
	private void updateLabels(){
		clear();
		Label title = new Label("List of all Persons");
		add(title);
		for(PersonMirror p : persons){
			Label l = new Label(p.getName()+" "+p.getFirstname());
			ClickHandler clickHandler = new ClickHandlerPerson(p, mainPanel);
			l.addClickHandler(clickHandler);
			add(l);
		}
		addCreationLink();
	}
	
	
}
